package com.aqielife.netty.simple;

import com.aqielife.netty.simple.handler.WebsocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ImServer {
    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);

    public static final ChannelGroup GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void start() throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // http 编码解码器
                            pipeline.addLast(new HttpServerCodec())
                                    // 支持大数据流
                                    .addLast(new ChunkedWriteHandler())
                                    // http 消息聚合
                                    .addLast(new HttpObjectAggregator(1024 * 63))
                                    .addLast(new WebSocketServerProtocolHandler("/ws"))
                                    .addLast(new WebsocketHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(10010).sync();
            // 关闭通道
            // future.channel().closeFuture().sync();
        } finally {
//            boss.shutdownGracefully();
//            work.shutdownGracefully();
        }
    }
}
